package com.UKIT.airtickets.Activities.fragments

import TicketAdapter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.UserFavorite
import com.UKIT.airtickets.Service.Handlers.MainFragmentHandler
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.Service.Tikets
import com.UKIT.airtickets.databinding.FragmentMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainFragment : Fragment(), TicketAdapter.OnFavoriteClickListener {

    private var _binding: FragmentMainBinding? = null
    private val binding get() = _binding!!

    private lateinit var ticketAdapter: TicketAdapter
    private lateinit var mainFragmentHandler: MainFragmentHandler

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mainFragmentHandler = MainFragmentHandler(requireContext())

        setupRecyclerView()

        binding.searchButton.setOnClickListener {
            val startCity = binding.startCity.text.toString()
            val endCity = binding.endCity.text.toString()
            loadData(startCity, endCity)
        }
    }

    private fun setupRecyclerView() {
        ticketAdapter = TicketAdapter(this, AppDatabase.getDatabase(requireContext()).userFavoriteDao())
        binding.tickets.apply {
            adapter = ticketAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
    }

    private fun loadData(startCity: String, endCity: String) {
        mainFragmentHandler.loadData(startCity, endCity) { tickets ->
            ticketAdapter.setData(tickets)
        }
    }

    override fun onFavoriteClick(ticket: Tikets) {
        CoroutineScope(Dispatchers.IO).launch {
            toggleFavoriteStatus(ticket)
        }
    }

    private suspend fun toggleFavoriteStatus(ticket: Tikets) {
        if (isInFavorites(ticket)) {
            removeTicketFromFavorites(ticket)
        } else {
            addTicketToFavorites(ticket)
        }
    }

    private fun isInFavorites(ticket: Tikets): Boolean {
        val searchToken = ticket.searchToken
        val userFavoriteDao = AppDatabase.getDatabase(requireContext()).userFavoriteDao()
        return userFavoriteDao.isFavorite(searchToken, SettingsApp.userId) > 0
    }

    private fun addTicketToFavorites(ticket: Tikets) {
        val userFavoriteDao = AppDatabase.getDatabase(requireContext()).userFavoriteDao()
        val userFavorite = UserFavorite(
            userId = SettingsApp.userId,
            searchToken = ticket.searchToken,
            startCity = ticket.startCity,
            startCityCode = ticket.startCityCode,
            endCity = ticket.endCity,
            endCityCode = ticket.endCityCode,
            startDate = ticket.startDate,
            endDate = ticket.endDate,
            price = ticket.price
        )
        userFavoriteDao.insertUserFavorite(userFavorite)
    }

    private suspend fun removeTicketFromFavorites(ticket: Tikets) {
        val searchToken = ticket.searchToken
        val userFavoriteDao = AppDatabase.getDatabase(requireContext()).userFavoriteDao()
        userFavoriteDao.deleteFavorite(searchToken)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
